package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.OSSUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.dto.DesignerAddDto;
import com.ruoyi.system.dto.DesignerSeleteDto;
import com.ruoyi.system.entity.ConstructionStageDO;
import com.ruoyi.system.mapper.CasesGenMapper;
import com.ruoyi.system.mapper.ConstructionStageMapper;
import com.ruoyi.system.mapper.DesignerGenMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.DesignerService;
import com.ruoyi.system.utils.BeanUtil;
import com.ruoyi.system.vo.DesignerDetailVo;
import com.ruoyi.system.domain.CasesGenExample;
import com.ruoyi.system.domain.DesignerGen;
import com.ruoyi.system.domain.DesignerGenExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DesignerImpl extends ServiceImpl<DesignerGenMapper, DesignerGen> implements DesignerService {
    @Resource
    private DesignerGenMapper designerGenMapper;
    @Resource
    private OSSUtils ossUtils;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private CasesGenMapper casesGenMapper;

    /**
     * 设计师新增
     * @param dto
     * @return
     */
    @Override
    public boolean addDesigner(MultipartFile file,DesignerAddDto dto) {
        OSSUtils.OssFileInfo fileInfo = ossUtils.upload(file, new String());
        String downloadUrl = fileInfo.getDownloadUrl();
        DesignerGen designerGen = new DesignerGen();
        BeanUtils.copyProperties(dto,designerGen);
        designerGen.setPic(downloadUrl);
        //生成表单主键id
        designerGen.setAliveFlag(1);
        designerGen.setPic(dto.getPic());
        try{
            designerGenMapper.insertSelective(designerGen);
        }catch (Exception e){
            log.info("获取当前新增设计师信息##异常##", e);
            return false;
        }
        return true;
    }

    /**
     * 设计师逻辑删除
     * @param id
     */
    @Override
    public boolean deleteDesigner(Long id) {
        DesignerGen designerGen = new DesignerGen();
        designerGen.setAliveFlag(0);
        DesignerGenExample designerGenExample = new DesignerGenExample();
        designerGenExample.createCriteria().andUserIdEqualTo(id);
        designerGenMapper.updateByExampleSelective(designerGen,designerGenExample);
        try{
            designerGenMapper.updateByExampleSelective(designerGen,designerGenExample);
        }catch (Exception e){
            log.info("获取当前同步逻辑删除设计师信息##异常##", e);
            return false;
        }
        return true;
    }

    /**
     * 设计师编辑
     * @param dto
     */
    @Override
    public boolean editDesigner(DesignerAddDto dto) {
        if (ObjectUtils.isEmpty(dto.getId())){
            return false;
        }
        DesignerGen designerGen = new DesignerGen();
        designerGen.setId(dto.getId());
        BeanUtils.copyProperties(dto,designerGen);
        if (!ObjectUtils.isEmpty(dto.getDesignStyle())){
            designerGen.setDesignStyle(dto.getDesignStyle().toString());
        }
        designerGenMapper.updateByPrimaryKeySelective(designerGen);
        return true;

    }

    /**
     * 设计师模糊搜索
     */
    @Override
    public List<DesignerDetailVo> queryDesigner(DesignerSeleteDto dto) {
        List<DesignerDetailVo> designerList = new ArrayList<>();
        DesignerGenExample designerGenExample = new DesignerGenExample();
        DesignerGenExample.Criteria criteria = designerGenExample.createCriteria();
        criteria.andAliveFlagEqualTo(1);
        if (dto.getNickName() != null && !dto.getNickName().trim().isEmpty()) {
            criteria.andNickNameLike("%" + dto.getNickName().trim() + "%");
        }
        if (!ObjectUtils.isEmpty(dto.getEmploymentAgeStart()) && !ObjectUtils.isEmpty(dto.getEmploymentAgeEnd())) {
            criteria.andEmploymentAgeBetween(dto.getEmploymentAgeStart(), dto.getEmploymentAgeEnd());
        }
        if (!ObjectUtils.isEmpty(dto.getDesignStyle())){
            List<String> designStyle = dto.getDesignStyle();
            for (int i = 0; i < designStyle.size(); i++) {
                criteria.andDesignStyleLike("%" + designStyle.get(i) + "%");
            }
        }
        if (!ObjectUtils.isEmpty(dto.getStatus()) && dto.getStatus().equals("0")){
            criteria.andStatusEqualTo("0");
        }
        if (!ObjectUtils.isEmpty(dto.getStatus()) && dto.getStatus().equals("1")){
            criteria.andStatusEqualTo("1");
        }
        if (!ObjectUtils.isEmpty(dto.getWorkTime())){
            LocalDate localDate = dto.getWorkTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            // 2. 获取当年最后一天（12月31日）
            LocalDate endOfYear = localDate.withMonth(12).withDayOfMonth(31);

            // 3. 转回Date类型（默认时间为00:00:00）
            Date lastDate = Date.from(endOfYear.atStartOfDay(ZoneId.systemDefault()).toInstant());
            criteria.andWorkTimeBetween(dto.getWorkTime(),lastDate);
        }

        // 判断是否需要根据推荐筛选
        if(!ObjectUtils.isEmpty(dto.getIsRecommende()) && dto.getIsRecommende().equals(1)){
            criteria.andIsRecommendeEqualTo(1);
        }
        if(!ObjectUtils.isEmpty(dto.getIsRecommende()) && dto.getIsRecommende().equals(0)){
            criteria.andIsRecommendeEqualTo(0);
        }
        // 3. 查询分页数据
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<DesignerGen> designerGens = designerGenMapper.selectByExample(designerGenExample);
        if (!ObjectUtils.isEmpty(designerGens)){
            for (int i = 0; i < designerGens.size(); i++) {
                DesignerDetailVo designerDetailVo = new DesignerDetailVo();
                BeanUtil.copyProperties(designerGens.get(i),designerDetailVo);
                String designStyleCode = designerGens.get(i).getDesignStyle();
                if (!ObjectUtils.isEmpty(designStyleCode)){
                    // 1. 去除首尾的方括号
                    String content = designStyleCode.substring (1, designStyleCode.length () - 1);
                    // 2. 按逗号分割，去除空格，收集为 List<String>
                    List<String> result = Arrays.stream (content.split (","))
                            .map (String::trim) // 去除每个元素的前后空格
                            .collect (Collectors.toList ()); // 收集为 List<String>
                    designerDetailVo.setDesignStyle(result);
                    designerList.add(i,designerDetailVo);
                }else {
                    designerList.add(i,designerDetailVo);
                }

            }
        }
        for (DesignerDetailVo item : designerList) {
            CasesGenExample casesGenExample = new CasesGenExample();
            casesGenExample.createCriteria().andDesignerEqualTo(item.getId()).andAliveFlagEqualTo("1");
            long count = casesGenMapper.countByExample(casesGenExample);
            item.setCaseNumber(count);
        }

        return designerList;
    }

    /**
     * 设计师推荐值排序
     * @return
     */
    @Override
    public List<DesignerDetailVo> queryDesignerByValue() {
        List<DesignerDetailVo> designerList = new ArrayList<>();

        DesignerGenExample designerGenExample = new DesignerGenExample();
        designerGenExample.createCriteria().andAliveFlagEqualTo(1);
        designerGenExample.createCriteria().andStatusEqualTo("0");
        designerGenExample.setOrderByClause("recommende_value ASC");
        List<DesignerGen> designerGens = designerGenMapper.selectByExample(designerGenExample);
        if (!ObjectUtils.isEmpty(designerGens)){
            BeanUtil.copyListProperties(designerGens,designerList, DesignerDetailVo.class);
        }
        return designerList;
    }

    @Override
    public DesignerDetailVo queryDesignerDetail(String id) {
        DesignerDetailVo designerDetailVo = new DesignerDetailVo();
        Long designerId = Long.parseLong(id);
        DesignerGen designerGen = designerGenMapper.selectByPrimaryKey(designerId);
        if (!ObjectUtils.isEmpty(designerGen)){
            BeanUtils.copyProperties(designerGen,designerDetailVo);
        }
        if(!ObjectUtils.isEmpty(designerGen.getDesignStyle())){
            String designStyleCode = designerGen.getDesignStyle();
            // 1. 去除首尾的方括号
            String content = designStyleCode.substring (1, designStyleCode.length () - 1);
            // 2. 按逗号分割，去除空格，收集为 List<String>
            List<String> result = Arrays.stream (content.split (","))
                    .map (String::trim) // 去除每个元素的前后空格
                    .collect (Collectors.toList ()); // 收集为 List<String>
            designerDetailVo.setDesignStyle(result);
        }
        return designerDetailVo;
    }

    @Override
    public boolean synchronizeDesigner(Long id) {
        SysUser sysUser = sysUserMapper.selectUserById(id);

        DesignerGenExample designerGenExample = new DesignerGenExample();
        DesignerGenExample.Criteria criteria = designerGenExample.createCriteria().andUserIdEqualTo(id);
        List<DesignerGen> designerGens = designerGenMapper.selectByExample(designerGenExample);
        try{
            //如果当前用户id没有在designer表中查到 就新增
            if (ObjectUtils.isEmpty(designerGens)){
                DesignerGen designerGen = new DesignerGen();
                BeanUtils.copyProperties(sysUser,designerGen);
                designerGen.setAliveFlag(1);
                designerGenMapper.insertSelective(designerGen);
            }else {
                //如果当前用户id在designer表中查到了 就修改
                DesignerGen designerGen = new DesignerGen();
                BeanUtils.copyProperties(sysUser,designerGen);
                designerGenMapper.updateByExampleSelective(designerGen,designerGenExample);
            }
        }catch (Exception e){
            log.info("获取当前同步新增设计师信息##异常##", e);
            return false;
        }
        return true;
    }
}
